#!/usr/bin/env python3
import os
import sys
import json
import platform
from pathlib import Path

class IDEAProxySetup:
    def __init__(self, proxy_host="127.0.0.1", proxy_port=8080):
        self.proxy_host = proxy_host
        self.proxy_port = proxy_port
        self.system = platform.system().lower()
        
    def get_idea_config_paths(self):
        """Get IDEA configuration directory paths for different OS"""
        home = Path.home()
        
        if self.system == "windows":
            appdata = os.getenv('APPDATA', home / 'AppData' / 'Roaming')
            return [
                Path(appdata) / 'JetBrains' / 'IntelliJIdea2023.3',
                Path(appdata) / 'JetBrains' / 'IntelliJIdea2023.2',
                Path(appdata) / 'JetBrains' / 'IntelliJIdea2023.1',
            ]
        elif self.system == "darwin":  # macOS
            return [
                home / 'Library' / 'Application Support' / 'JetBrains' / 'IntelliJIdea2023.3',
                home / 'Library' / 'Application Support' / 'JetBrains' / 'IntelliJIdea2023.2',
                home / 'Library' / 'Application Support' / 'JetBrains' / 'IntelliJIdea2023.1',
            ]
        else:  # Linux
            return [
                home / '.config' / 'JetBrains' / 'IntelliJIdea2023.3',
                home / '.config' / 'JetBrains' / 'IntelliJIdea2023.2',
                home / '.config' / 'JetBrains' / 'IntelliJIdea2023.1',
                home / '.IntelliJIdea2023.3',
                home / '.IntelliJIdea2023.2',
                home / '.IntelliJIdea2023.1',
            ]

    def find_idea_config(self):
        """Find the active IDEA configuration directory"""
        for config_path in self.get_idea_config_paths():
            if config_path.exists():
                print(f"Found IDEA config at: {config_path}")
                return config_path
        return None

    def create_proxy_config(self, config_dir):
        """Create proxy configuration for IDEA"""
        options_dir = config_dir / 'options'
        options_dir.mkdir(exist_ok=True)
        
        proxy_settings = {
            "USE_HTTP_PROXY": True,
            "USE_PROXY_PAC": False,
            "USE_PAC_URL": False,
            "PROXY_HOST": self.proxy_host,
            "PROXY_PORT": self.proxy_port,
            "PROXY_AUTHENTICATION": False,
            "PROXY_LOGIN": "",
            "PROXY_PASSWORD_CRYPT": "",
            "USE_SOCKS": False,
            "SOCKS_HOST": "",
            "SOCKS_PORT": 1080,
            "SOCKS_AUTHENTICATION": False,
            "SOCKS_LOGIN": "",
            "SOCKS_PASSWORD_CRYPT": "",
            "KEEP_PROXY_PASSWORD": False,
            "PROXY_EXCEPTIONS": "localhost,127.0.0.1"
        }
        
        proxy_file = options_dir / 'proxy.settings.xml'
        xml_content = self.generate_proxy_xml(proxy_settings)
        
        with open(proxy_file, 'w') as f:
            f.write(xml_content)
        
        print(f"Proxy configuration written to: {proxy_file}")

    def generate_proxy_xml(self, settings):
        """Generate IDEA proxy settings XML"""
        return f"""<?xml version="1.0" encoding="UTF-8"?>
<application>
  <component name="HttpConfigurable">
    <option name="USE_HTTP_PROXY" value="{str(settings['USE_HTTP_PROXY']).lower()}" />
    <option name="USE_PROXY_PAC" value="{str(settings['USE_PROXY_PAC']).lower()}" />
    <option name="USE_PAC_URL" value="{str(settings['USE_PAC_URL']).lower()}" />
    <option name="PROXY_HOST" value="{settings['PROXY_HOST']}" />
    <option name="PROXY_PORT" value="{settings['PROXY_PORT']}" />
    <option name="PROXY_AUTHENTICATION" value="{str(settings['PROXY_AUTHENTICATION']).lower()}" />
    <option name="PROXY_LOGIN" value="{settings['PROXY_LOGIN']}" />
    <option name="PROXY_PASSWORD_CRYPT" value="{settings['PROXY_PASSWORD_CRYPT']}" />
    <option name="USE_SOCKS" value="{str(settings['USE_SOCKS']).lower()}" />
    <option name="SOCKS_HOST" value="{settings['SOCKS_HOST']}" />
    <option name="SOCKS_PORT" value="{settings['SOCKS_PORT']}" />
    <option name="SOCKS_AUTHENTICATION" value="{str(settings['SOCKS_AUTHENTICATION']).lower()}" />
    <option name="SOCKS_LOGIN" value="{settings['SOCKS_LOGIN']}" />
    <option name="SOCKS_PASSWORD_CRYPT" value="{settings['SOCKS_PASSWORD_CRYPT']}" />
    <option name="KEEP_PROXY_PASSWORD" value="{str(settings['KEEP_PROXY_PASSWORD']).lower()}" />
    <option name="PROXY_EXCEPTIONS" value="{settings['PROXY_EXCEPTIONS']}" />
  </component>
</application>"""

    def setup(self):
        """Main setup function"""
        print("IDEA Proxy Setup")
        print("================")
        print(f"Setting up proxy: {self.proxy_host}:{self.proxy_port}")
        
        config_dir = self.find_idea_config()
        if not config_dir:
            print("ERROR: Could not find IDEA configuration directory")
            print("Please make sure IntelliJ IDEA is installed and has been run at least once")
            return False
        
        try:
            self.create_proxy_config(config_dir)
            print("\nSetup completed successfully!")
            print("\nNext steps:")
            print("1. Start the proxy: python3 idea_proxy.py")
            print("2. Restart IntelliJ IDEA")
            print("3. The proxy will intercept and log all network requests")
            print("4. Check idea_proxy.log for request logs")
            return True
        except Exception as e:
            print(f"ERROR: Setup failed: {e}")
            return False

    def remove_proxy_config(self):
        """Remove proxy configuration"""
        config_dir = self.find_idea_config()
        if config_dir:
            proxy_file = config_dir / 'options' / 'proxy.settings.xml'
            if proxy_file.exists():
                proxy_file.unlink()
                print("Proxy configuration removed")
            else:
                print("No proxy configuration found")


if __name__ == '__main__':
    import argparse
    
    parser = argparse.ArgumentParser(description='Setup IDEA proxy configuration')
    parser.add_argument('--host', default='127.0.0.1', help='Proxy host (default: 127.0.0.1)')
    parser.add_argument('--port', type=int, default=8080, help='Proxy port (default: 8080)')
    parser.add_argument('--remove', action='store_true', help='Remove proxy configuration')
    
    args = parser.parse_args()
    
    setup = IDEAProxySetup(args.host, args.port)
    
    if args.remove:
        setup.remove_proxy_config()
    else:
        setup.setup()